package com.vegetable.modules.controller.quotation;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.style.StyleUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vegetable.common.utils.ExcelUtils;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.baseData.BaseDict;
import com.vegetable.modules.entity.quotation.Quotation;
import com.vegetable.modules.entity.quotation.QuotationArea;
import com.vegetable.modules.entity.quotation.QuotationLog;
import com.vegetable.modules.entity.quotation.export.QuotationExport;
import com.vegetable.modules.entity.quotation.po.QuotationAreaAddPO;
import com.vegetable.modules.entity.quotation.po.QuotationPO;
import com.vegetable.modules.entity.quotation.po.QuotationQueryPO;
import com.vegetable.modules.service.baseData.IBaseDictService;
import com.vegetable.modules.service.quotation.IQuotationAreaService;
import com.vegetable.modules.service.quotation.IQuotationLogService;
import com.vegetable.modules.service.quotation.IQuotationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/quotation")
//@AllArgsConstructor
@Api(value = "报价单", tags = "报价单")
public class QuotationController extends AbstractController {
    @Resource
    private IBaseDictService iBaseDictService;
    @Resource
    private IQuotationService iQuotationService;
    @Resource
    private IQuotationLogService iQuotationLogService;
    @Resource
    private IQuotationAreaService iQuotationAreaService;




    /**
     * 查询报价区域列表
     * @return
     */
    @GetMapping("/areaList")
    @ApiOperation(value = "查询报价区域列表", notes = "查询报价区域列表", response = QuotationArea.class)
    public R areaList(String areaNameLike, Boolean isEmpty){
        // 当前登陆用户的手机号
        String mobile = getUser().getMobile();
        List<QuotationArea> areas = iQuotationAreaService.quotationAreaList(areaNameLike, mobile, isEmpty);
        log.info("报价大区列表: ---- >{}", JSONArray.toJSONString(areas));
        return R.data(areas);
    }

    @GetMapping("/areaAdd")
    @ApiOperation(value = "新增报价区域", notes = "新增报价区域")
    public R areaAdd(@RequestBody QuotationAreaAddPO po){
        int res = iQuotationAreaService.add(po);
        log.info("新增大区: ---- >{}", res);
        return R.data(res);
    }
    /**
     * 筛选/查看报价单列表
     * @param param
     * @return
     */
    @PostMapping("/list")
    @ApiOperation(value = "查询报价单列表", notes = "查询报价单列表", response = Quotation.class)
    public R quotationList(@RequestBody QuotationQueryPO param){
        List<Map<String, Object>> result = new ArrayList<>();
        Quotation quotation = new Quotation();
        BeanUtils.copyProperties(param, quotation);
        List<Quotation> quotations = iQuotationService.quotationList(param);
        // 查询报价单商品最近两天涨幅情况
        List<Long> ids = quotations.stream().map(Quotation::getId).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(ids)){
            QueryWrapper<QuotationLog> logQuery = new QueryWrapper<QuotationLog>().
                    in("quotation_id", ids).
                    in("order_time", DateUtil.formatDate(DateUtil.yesterday()), DateUtil.formatDate(new Date())).
                    orderByDesc("order_time");
            List<QuotationLog> logs = iQuotationLogService.list(logQuery);
            for (Quotation quo : quotations){
                List<QuotationLog> qLogs = logs.stream().filter(en -> en.getQuotationId().equals(quo.getId())).collect(Collectors.toList());
                // 如果报价日志列表为空 或者 数量大于1,则对比价格趋势
                if(CollectionUtil.isNotEmpty(qLogs)){
                    QuotationLog tPrice = qLogs.stream().filter(el -> DateUtil.formatDate(el.getOrderTime()).equals(DateUtil.formatDate(new Date()))).findAny().orElse(null);
                    QuotationLog yPrice = qLogs.stream().filter(el -> DateUtil.formatDate(el.getOrderTime()).equals(DateUtil.formatDate(DateUtil.yesterday()))).findAny().orElse(null);
                    if(ObjectUtil.isNotNull(yPrice) && ObjectUtil.isNotNull(tPrice)){
                        int compareRes = NumberUtil.compare(tPrice.getTopPrice().doubleValue(), yPrice.getTopPrice().doubleValue());
                        quo.setPriceTrend(compareRes);
                        quo.setPriceDiff(NumberUtil.sub(tPrice.getTopPrice(), yPrice.getTopPrice()));
                    } else if (ObjectUtil.isNotNull(tPrice)) {
                        quo.setPriceTrend(1);
                        quo.setPriceDiff(quo.getTopPrice());
                    }
                }
            }
            quotations.sort(Comparator.comparing(Quotation::getSort));
            // 报价商品按照类型分组
            Map<String, List<Quotation>> listMap = quotations.stream().sorted(Comparator.comparingInt(Quotation::getSort)).collect(Collectors.groupingBy(Quotation::getProductType, LinkedHashMap::new, Collectors.toList()));
            for(Map.Entry<String, List<Quotation>> en : listMap.entrySet()){
                Map<String, Object> map = new HashMap<>();
                map.put("productType", en.getKey());
                map.put("productData", en.getValue());
                result.add(map);
            }
        }
        log.info("查询报价单列表{}", JSON.toJSONString(param));
        return R.data(result);
    }

    /**
     * 新增报价单
     * @param param
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "新增报价单", notes = "新增报价单")
    public R addQuotation(@RequestBody QuotationPO param){
        iQuotationService.saveQuotation(param);
        return R.success("报价新增成功");
    }

    /**
     * 更新报价单
     * @param param
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "条件查询销售出库列表", notes = "条件查询销售出库列表")
    public R updateQuotation(@RequestBody QuotationPO param){
        if(ObjectUtil.isNull(param.getLowPrice()) && ObjectUtil.isNull(param.getTopPrice())){
            return R.fail("最高价格/最低价格不能同时为空");
        }
        if(ObjectUtil.isNull(param.getLowPrice())){
            param.setLowPrice(param.getTopPrice());
        }
        if(ObjectUtil.isNull(param.getTopPrice())){
            param.setTopPrice(param.getLowPrice());
        }
        log.info("新增报价单 --> {}", JSON.toJSONString(param));
        iQuotationService.updateQuotation(param);
        return R.data("");
    }

    @PostMapping("/typeList")
    @ApiOperation(value = "商品类型列表", notes = "商品类型列表")
    public R typeList(){
        List<BaseDict> baseDicts =  iBaseDictService.queryGoodsType();
        List<String> typeList = new ArrayList<>();
        for(BaseDict bd : baseDicts){
            typeList.add(bd.getValueOne());
        }
        return R.data(typeList);
    }



    @GetMapping("/exportQuotation")
    @ApiOperation(value = "导出报价单", notes = "导出报价单")
    @Deprecated
    public R exportQuotation() throws IOException {
        // 报价区域
        List<QuotationArea> areaList = iQuotationAreaService.list();
        QuotationQueryPO param = new QuotationQueryPO();
        param.setPageSize(Long.MAX_VALUE+"");
        param.setCurrentPage("1");
        List<Quotation> quotations = iQuotationService.quotationList(param);
        // 报价单按照区域分组
        Map<Long, List<Quotation>> areaMap = quotations.stream().collect(Collectors.groupingBy(Quotation::getAreaId));
        List<Map<String, Object>> sheetsList = new ArrayList<>();
        for(Map.Entry<Long, List<Quotation>> areaEn : areaMap.entrySet()){
            QuotationArea area = areaList.stream().filter(en -> en.getId().equals(areaEn.getKey())).findFirst().orElse(null);
            String sheetName = Objects.isNull(area)? "区域名称" : area.getAreaName();
            // quotation专程QuotationExport
            List<QuotationExport> exportList = new ArrayList<>();
            Map<String, List<Quotation>> toMap = areaEn.getValue().stream().collect(Collectors.groupingBy(Quotation::getProductType));
            for(Map.Entry<String, List<Quotation>> en : toMap.entrySet()){
                QuotationExport exportLine1 = new QuotationExport();
                exportLine1.setProductType(en.getKey());
                exportList.add(exportLine1);
                List<Quotation> values = en.getValue();
                for(Quotation q : values){
                    QuotationExport exportLine2 = new QuotationExport();
                    exportLine2.setProductType(q.getProductName());
//                    exportLine2.setProductName(q.getProductPrice().toEngineeringString());
                    exportList.add(exportLine2);
                }
            }
            int size = exportList.size();
            int groupSize = size / 3;
            List<List<QuotationExport>> temp = ListUtils.partition(exportList, groupSize);
            int tempSize = temp.size();
            List<QuotationExport> exportList1 = new ArrayList<>();
            exportList1.addAll(temp.get(0));
            if(tempSize > 1){
                for(int i = 0; i < exportList1.size() ; i++){
                    exportList1.get(i).setProductType1(temp.get(1).get(i).getProductType());
                    exportList1.get(i).setProductName1(temp.get(1).get(i).getProductName());
                }
            }
            if(tempSize > 2){
                for(int i = 0; i < exportList1.size() ; i++){
                    exportList1.get(i).setProductType2(temp.get(2).get(i).getProductType());
                    exportList1.get(i).setProductName2(temp.get(2).get(i).getProductName());
                }
            }
            ExportParams deptParams = new ExportParams();
            deptParams.setSheetName(sheetName);
            deptParams.setTitle("德硕报价单(" + area.getAreaName() + ")" + DateUtil.date().toDateStr());

            //创建sheet1使用多map
            Map<String,Object> deptMap = new HashMap<>();
            //title的参数为ExportParams类型
            deptMap.put("title",deptParams);
            //模版导出对应的实体类型
            deptMap.put("entity",QuotationExport.class);
            //sheet中要填充的数据
            deptMap.put("data",exportList1);
            sheetsList.add(deptMap);
        }
        Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
        workbook.createCellStyle();
        StyleUtil.createHeadCellStyle(workbook);

        String fileName = "报价单_" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        ExcelUtils.downLoadExcel(fileName,workbook);
        return R.success("");
    }
    @PostMapping("/log")
    @ApiOperation(value = "商品价格趋势", notes = "商品价格趋势")
    public R logList(){
        return R.data(null);
    }




}
